<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>getSnapshotBeforeUpdate</title>
    <style>
      div {
        width: 200px;
        height: 150px;
        background-color: pink;
        overflow: auto;
      }
      div > p {
        height: 30px;
        margin: 0;
      }
    </style>
  </head>
  <body>
    <div id="test"></div>

    <script src="../js/17.0.1/react.development.js"></script>
    <script src="../js/17.0.1/react-dom.development.js"></script>
    <script src="../js/17.0.1/babel.min.js"></script>

    <script type="text/babel">
      // 创建类式组件
      class NewsList extends React.Component {
        constructor(props) {
          console.log('constructor')
          super(props)

          // 初始化状态
          this.state = {
            newArr: []
          }
        }

        static getDerivedStateFromProps(props, state) {
          console.log('getDerivedStateFromPorps', props, state)
          return null
        }

        getSnapshotBeforeUpdate() {
          console.log('getSnapshotBeforeUpdate')
          return this.refs.list.scrollHeight
        }

        // 组件挂载完毕后调用
        componentDidMount() {
          console.log('componentDidMount')
          setInterval(() => {
            const { newArr } = this.state
            const news = '新闻' + (newArr.length + 1)
            this.setState({
              newArr: [news, ...newArr]
            })
          }, 1000)
        }

        // 组件更新完毕后加载
        componentDidUpdate(preProps, preState, snapshotValue) {
          // preProps, preState 为上一次的值（oldValue）
          // snapshotValue 为 getSnapshotBeforeUpdate 的返回值
          console.log('componentDidUpdate', preProps, preState, snapshotValue)
          this.refs.list.scrollTop +=
            this.refs.list.scrollHeight - snapshotValue
        }

        // 组价初次渲染、更新时调用
        render() {
          console.log('render')
          const { newArr } = this.state
          return (
            <div ref="list">
              {newArr.map((item) => {
                return <p key={item}>{item}</p>
              })}
            </div>
          )
        }
      }

      ReactDOM.render(<NewsList />, document.getElementById('test'))
    </script>
  </body>
</html>
